package com.hs.jhzd.service.task;

import com.hs.jhzd.entity.Fingerprint;
import com.hs.jhzd.entity.Prisoner;
import com.hs.jhzd.repository.PrisonerRepository;
import com.hs.jhzd.service.fp.FingerprintService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.caffeine.CaffeineCache;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Slf4j
@Data
@Service(value = "fingerprintTask")
public class FingerprintTask {

  @Autowired
  private FingerprintService fingerprintService;

  @Autowired
  private PrisonerRepository prisonerRepository;

  @Value("${jsbh}")
  private String jsbh;

  private CaffeineCache fingerprintCache;

  @Autowired
  private CacheManager cacheManager;

  @Scheduled(cron = "* 0/10 * * * *")
  public void run() {
    log.debug("指纹定时任务开始运行...");
    fingerprintCache = (CaffeineCache) cacheManager.getCache("fingerprintCache");

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -11);
    List<Fingerprint> fingerprints = fingerprintService.getFingerprint2Add(jsbh, calendar.getTime());
    if (!CollectionUtils.isEmpty(fingerprints)) {
      fingerprints.forEach(f -> {

            Prisoner prisoner = prisonerRepository.findByRybh(f.getRybh());
            if (prisoner != null) {
              List<Fingerprint> fps = fingerprintCache.get(prisoner.getJsh(), List.class);
              if (fps == null) {
                fps = new ArrayList<>();
              }
              fps.add(f);
              fingerprintCache.put(prisoner.getJsh(), fingerprints);
            }

      });
    }

  }

}
